﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace ConnectFour
{
    class FileBasedPlayer : Player
    {
        private const String MOVE_FILE = "move", BOARD_FILE = "board", GAME_OVER_FILE = "gameover";

        public FileBasedPlayer(Checker myColor, Board board, String myDirectory) : base(myColor, board, myDirectory) 
        {
            if (!Directory.Exists(myDirectory))
            {
                Directory.CreateDirectory(myDirectory);
            }
        }

        public override void GameOver(Checker winner) {
            using (StreamWriter stream = new StreamWriter(myDirectory + Path.DirectorySeparatorChar + GAME_OVER_FILE))
            {
                stream.Write(winner == myColor ? "W" : "L");
            }
        }

        public override int Move(int lastMove)
        {
            StringBuilder output = new StringBuilder(board.ToString());
            int move;
            output.Append(myColor == Checker.Red ? 'R' : 'B');
            output.Append((char)(lastMove + '0' + 1));

            using (StreamWriter stream = new StreamWriter(myDirectory + Path.DirectorySeparatorChar + BOARD_FILE))
            {
                stream.Write(output.ToString());
            }

            while (!File.Exists(myDirectory + Path.DirectorySeparatorChar + MOVE_FILE)) ;

            Thread.Sleep(500);

            using (StreamReader stream = new StreamReader(myDirectory + Path.DirectorySeparatorChar + MOVE_FILE))
            {
                move = stream.ReadLine()[0] - '0' - 1;
            }

            File.Delete(myDirectory + Path.DirectorySeparatorChar + MOVE_FILE);
            return move;
        }
    }
}
